<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Service_Alipay extends Stourweb_Controller
{

    /**
     * API直连接口
     */
    protected $_client_id = "";
    protected $_clinet_secret_key = "";
    protected $_host = "";
    protected $_version = "1.0";

    public function before()
    {
        parent::before();

    }

    public function action_index()
    {

        //兼容写法
        if (empty($_POST))
        {
            $_POST = json_decode(file_get_contents('php://input'), true);

        }
        $site_id = intval($_POST['siteId']);
        $secret = St_Filter::remove_xss($_POST['secret']);
        if (empty($site_id))
        {
            echo json_encode(array('status' => 0, 'msg' => '站点id不能为空'));
            return;
        }
        //获取接口信息
        $api = $this->get_api_info($site_id,$secret);
        if(!isset($api['id']))
        {
            echo json_encode(array('status' => 0, 'msg' => '通信密钥错误'));
            return;
        }
        $this->_client_id = $api['id'];
        $this->_clinet_secret_key = $api['secret_key'];
        $this->_host =  $_SERVER['HTTP_HOST'];
        $method = $_POST['method'];
        if (isset($_POST['token']))
        {
            $token_arr = explode('||', Common::authcode($_POST['token'],'DECODE'));
            $_POST['openid'] = $token_arr[0];
            $_POST['session_key'] = $token_arr[1];
        }
        $request_result = $this->send_request($method, $_POST);


        if ($request_result['success'] == false)
        {
            echo json_encode(array('status' => 0, 'msg' => $request_result['message']));
            return;
        }
        else
        {
            echo json_encode(array('status' => 1, 'data' => $request_result['body']->content));
            return;
        }
    }


    protected function get_api_info($site_id,$secret)
    {
        return DB::select()->from('api_client')
            ->where('id','=',$site_id)
            ->and_where('secret_key','=',$secret)
            ->execute()
            ->current();


    }

    protected function send_request($method, $params)
    {
        $request_result = array(
            'success' => false,
            'message' => '',
            'body' => null
        );

        $api_envelope = array(
            'version' => $this->_version,
            'body' => null,
            'signature' => ""
        );

        $api_envelope_body = array(
            'client_id' => $this->_client_id,
            'success' => true,
            'message' => "",
            'timestamp' => time(),
            'content' => $params
        );

        $api_envelope['body'] = base64_encode(json_encode($api_envelope_body));
        $api_envelope['signature'] = md5($api_envelope['body'] . $this->_clinet_secret_key);
        $request_param = json_encode($api_envelope);
        $uri = trim($this->_host) . "/{$method}";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_param);
        $return = curl_exec($ch);
        curl_close($ch);
        $return = trim($return,chr(239).chr(187).chr(191));
        $return_object = json_decode($return);
        if (!is_object($return_object))
        {
            $message =  "请求返回的报文格式不正确";
            // 添加调试模式
            $devmode = isset($params['develop']) ? $params['develop'] : '';
            if($devmode)
            {

                $message = $return;
            }
            $request_result['message'] = $message;
            return $request_result;
        }

        if ($return_object->version != $this->_version)
        {
            $request_result['message'] = "报文版本号不匹配";
            return $request_result;
        }

        if ($return_object->signature != md5($return_object->body . $this->_clinet_secret_key))
        {
            $request_result['message'] = "签名认证失败";
            return $request_result;
        }

        $request_result['body'] = json_decode(base64_decode($return_object->body));
        if ($request_result['body']->success == false)
        {
            $request_result['message'] = $request_result['body']->message;
            return $request_result;
        }

        $request_result['success'] = true;
        return $request_result;
    }




    public function action_qrcode2()
    {
        $imgUrl = $_GET['weburl'];
        $mime = $this->_get_mime($imgUrl);
        header("Content-type:image/jpeg");
        ob_clean();
        echo  file_get_contents($imgUrl);
    }
    //获取图像mime类型
    public function _get_mime($file)
    {
        $ext = substr($file, strrpos($file, '.')+1);
        switch ($ext)
        {
            case 'png':
                $mime = 'image/png';
                break;
            case 'gif':
                $mime = 'image/gif';
                break;
            default:
                $mime = 'image/jpeg';
                break;
        }
        return $mime;
    }

    public function action_download()
    {
        $str = date('YmdHis').'.docx';
        $file_path = $_GET['file'];
        //以只读和二进制模式打开文件
        $file = fopen ( $file_path, "r" );
        echo file_get_contents($file_path);
        //告诉浏览器这是一个文件流格式的文件
        Header ( "Content-type: application/octet-stream" );
        //请求范围的度量单位
        Header ( "Accept-Ranges: bytes" );
        //Content-Length是指定包含于请求或响应中数据的字节长度
        Header ( "Accept-Length: " . file_get_contents ( $file_path ) );
        //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
        Header ( "Content-Disposition: attachment; filename=" . $str );
        //读取文件内容并直接输出到浏览器
        echo fread ( $file, file_get_contents ( $file_path ) );
        fclose ( $file );
        exit ();
    }


}